@using Microsoft.AspNetCore.Components.Authorization
@using MyBlogServer.Services
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject NavigationManager Navigation
@inject IJwtAuthService JwtAuthService

<div>
    @if (_isAuthorized)
    {
        @ChildContent
    }
    else if (_isAuthorizedChecked)
    {
        @* 只有在检查完成后才执行重定向 *@
        <text>
        @{
            // 检查当前是否已经在登录页面，避免重定向循环
            var currentUri = Navigation.ToAbsoluteUri(Navigation.Uri);
            var isLoginPage = currentUri.AbsolutePath.Equals("/admin/login", StringComparison.OrdinalIgnoreCase);
            
            if (!isLoginPage)
            {
                Console.WriteLine("用户未授权，重定向到登录页面");
                Navigation.NavigateTo("/admin/login");
            }
            else
            {
                // 如果已经在登录页面，则显示内容
                @ChildContent
            }
        }
        </text>
    }
    else
    {
        <p>正在验证权限...</p>
    }
</div>

@code {
    [Parameter] public RenderFragment? ChildContent { get; set; }

    private bool _isAuthorized = false;
    private bool _isAuthorizedChecked = false;
    private bool _isCheckingAuth = false;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender && !_isCheckingAuth)
        {
            _isCheckingAuth = true;
            // 在组件首次渲染后执行JS调用
            await CheckAuthorization();
            
            // 在检查后再次检查授权状态，确保状态同步
            if (!_isAuthorized && _isAuthorizedChecked)
            {
                // 检查当前是否已经在登录页面，避免重定向循环
                var currentUri = Navigation.ToAbsoluteUri(Navigation.Uri);
                var isLoginPage = currentUri.AbsolutePath.Equals("/admin/login", StringComparison.OrdinalIgnoreCase);
                
                if (!isLoginPage)
                {
                    Console.WriteLine("用户未授权，重定向到登录页面 (OnAfterRender)");
                    Navigation.NavigateTo("/admin/login");
                }
            }

            StateHasChanged();
        }
    }

    private async Task CheckAuthorization()
    {
        try
        {
            // 检查JWT Token状态
            var token = await JwtAuthService.GetStoredTokenAsync();
            _isAuthorized = !string.IsNullOrEmpty(token) && await JwtAuthService.IsTokenValidAsync();
            
            if (_isAuthorized)
            {
                var username = await JwtAuthService.GetUsernameFromTokenAsync(token);
                Console.WriteLine($"JWT认证状态: {_isAuthorized}, 用户: {username}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"检查认证状态时发生错误: {ex.Message}");
            _isAuthorized = false;
        }
        
        _isAuthorizedChecked = true;
    }
}